package me.mononin.common.factory.presenter;

import android.support.v7.util.DiffUtil;

import net.qiujuer.genius.kit.handler.Run;
import net.qiujuer.genius.kit.handler.runable.Action;

import java.util.List;

import me.mononin.common.common.widget.recycler.RecyclerAdapter;

/**
 * 对于RecyclerView进行一次简单的Presenter封装
 */
public class BaseRecyclerPresenter<ViewModel, View extends BaseContract.RecyclerView>
        extends BasePresenter<View> {


    public BaseRecyclerPresenter(View view) {
        super(view);
    }

    /**
     * 刷新一组新的数据在界面中
     * @param list 数据集合
     */
    protected void refreshData(final List<ViewModel> list){
        //在主线程中执行
        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                View view = getView();
                if (view==null){
                    return;
                }
                //基本的更新数据并刷新界面
                RecyclerAdapter<ViewModel> adapter = view.getRecyclerAdapter();
                adapter.replace(list);
                view.onAdapterDataChanged();
            }
        });

    }

    protected void refreshData(final DiffUtil.DiffResult diffResult,final List<ViewModel> list){
        //
        Run.onUiAsync(new Action() {
            @Override
            public void call() {
                refreshDateOnUiThread(diffResult,list);
            }
        });
    }

    private void refreshDateOnUiThread(final DiffUtil.DiffResult diffResult,
                                       final List<ViewModel> list){
        View view = getView();
        if (view==null){
            return;
        }
        //获取适配器
        RecyclerAdapter<ViewModel> adapter = view.getRecyclerAdapter();
        //改变数据集合但不刷新界面
        adapter.getItems().clear();
        adapter.getItems().addAll(list);
        //通知界面更新
        view.onAdapterDataChanged();

        //进行增量更新
        diffResult.dispatchUpdatesTo(adapter);
    }
}
